package cn.itcast.web.shiro;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 自定义的realm，用来访问认证授权的数据
 * Realm: access your security data
 */
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private ModuleService moduleService;


    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //转换
         UsernamePasswordToken upToken = (UsernamePasswordToken) token;
         //2.获取用户输入的用户名
         String email = upToken.getUsername();
         //3.查询
         User user = userService.findByEmail(email);
         //4.判断用户名是否存在
        if(user == null){
            return null;
        }
        //5. 获取数据库中正确的密码
         String dbPwd = user.getPassword();
        //6.返回
        // 参数1：用户的身份，通过subject.getPrincipal()获取的就是这里的参数1
        // 参数2：数据库中正确的密码告诉shiro。shiro会自动校验（用户输入的密码、数据库中的密码）
        // 参数3：realm名称; getName() 获取默认名称。
         SimpleAuthenticationInfo sai = new SimpleAuthenticationInfo(user, dbPwd, getName());

        return sai;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        //1.获取认证后的身份对象
        User user = (User) principals.getPrimaryPrincipal();
        //2.根据登陆用户，查询权限
        List<Module> list = moduleService.findModuleByUserId(user.getId());
        //3.返回，告诉shiro用户拥有什么权限
        SimpleAuthorizationInfo sai = new SimpleAuthorizationInfo();
        if(list!=null &&list.size()>0){
            for (Module lists : list) {
                //添加权限
                sai.addStringPermission(lists.getName());
            }
        }

        return sai;
    }


}
